import { DataSource } from './DataSource';

/**
 * DataService class - Manages DataSource instances for the application.
 */
export class DataService {
  private static _instance: DataService;
  private _baseUrl: string = '';
  private _dataSources: Map<string, DataSource> = new Map();

  /**
   * Get the singleton instance of the DataService
   */
  public static getInstance(): DataService {
    if (!DataService._instance) {
      DataService._instance = new DataService();
    }
    return DataService._instance;
  }

  private constructor() {
    // Private constructor to enforce singleton pattern
  }

  /**
   * Initialize the data service
   * @param baseUrl The base URL for the API
   */
  public initialize(baseUrl: string): void {
    this._baseUrl = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;
  }

  /**
   * Get the base URL for the API
   */
  public get baseUrl(): string {
    return this._baseUrl;
  }

  /**
   * Get or create a DataSource for a business object type
   * @param objectTypeName The name of the business object type
   */
  public getDataSource(objectTypeName: string): DataSource {
    if (!this._dataSources.has(objectTypeName)) {
      const dataSource = new DataSource(objectTypeName, this._baseUrl);
      this._dataSources.set(objectTypeName, dataSource);
    }
    
    return this._dataSources.get(objectTypeName)!;
  }

  /**
   * Check if a DataSource exists for a business object type
   * @param objectTypeName The name of the business object type
   */
  public hasDataSource(objectTypeName: string): boolean {
    return this._dataSources.has(objectTypeName);
  }

  /**
   * Remove a DataSource
   * @param objectTypeName The name of the business object type
   */
  public removeDataSource(objectTypeName: string): boolean {
    return this._dataSources.delete(objectTypeName);
  }

  /**
   * Get all DataSource instances
   */
  public getAllDataSources(): DataSource[] {
    return Array.from(this._dataSources.values());
  }
}
